package com.chenyue.cm.live.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.live.dao.ex.LiveRecordMapperEx;
import com.chenyue.cm.live.domain.JdLiveRecord;
import com.chenyue.cm.live.service.JdLiveRecordService;
import com.chenyue.cm.live.vo.LiveList;
import com.chenyue.cm.live.vo.param.SetMatchLiveUser;
import com.chenyue.cm.match.dao.FormatLiveUserMapper;
import com.chenyue.cm.match.dao.JdMatchGroupUserMapper;
import com.chenyue.cm.match.dao.JdMatchLiveUserMapper;
import com.chenyue.cm.match.domain.FormatLiveUser;
import com.chenyue.cm.match.domain.JdMatchGroupUser;
import com.chenyue.cm.match.domain.JdMatchLiveUser;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;


/**
 * @author chenyue-cm
 */
@Service(value = "JdLiveRecordService")
public class JdLiveRecordServiceImpl extends BaseServiceImpl<JdLiveRecord> implements JdLiveRecordService {

    private final LiveRecordMapperEx liveRecordMapperEx;

    private final JdMatchLiveUserMapper matchLiveUserMapper;

    private final JdMatchGroupUserMapper matchGroupUserMapper;

    private final FormatLiveUserMapper formatLiveUserMapper;

    public JdLiveRecordServiceImpl(
            LiveRecordMapperEx liveRecordMapperEx,
            @Qualifier("jdMatchLiveUserMapper") JdMatchLiveUserMapper matchLiveUserMapper,
            @Qualifier("jdMatchGroupUserMapper") JdMatchGroupUserMapper matchGroupUserMapper,
            @Qualifier("formatLiveUserMapper") FormatLiveUserMapper formatLiveUserMapper
    ) {
        this.liveRecordMapperEx = liveRecordMapperEx;
        this.matchLiveUserMapper = matchLiveUserMapper;
        this.matchGroupUserMapper = matchGroupUserMapper;
        this.formatLiveUserMapper = formatLiveUserMapper;
    }

    @Override
    @Resource(name = "jdLiveRecordMapper")
    public void setBaseMapper(LcBaseMapper<JdLiveRecord, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    /**
     * 分配参赛员
     *
     * @param matchLiveUser 参赛员
     */
    @Override
    public void setMatchLiveUser(SetMatchLiveUser matchLiveUser) {
        if (matchLiveUser.getMatchType() == 1) {
            for (Integer userId : matchLiveUser.getLiveUserList()) {
                final JdMatchLiveUser one = matchLiveUserMapper.selectOne(
                        new LambdaQueryWrapper<JdMatchLiveUser>()
                                .eq(JdMatchLiveUser::getFormatId, matchLiveUser.getFormatArrangeId())
                                .eq(JdMatchLiveUser::getUserId, userId)
                                .last(" limit 1")
                );
                if (one != null) {
                    continue;
                }
                final FormatLiveUser member = formatLiveUserMapper.selectOne(
                        new LambdaQueryWrapper<FormatLiveUser>()
                                .eq(FormatLiveUser::getFormatId, matchLiveUser.getFormatArrangeId())
                                .eq(FormatLiveUser::getUserId, userId)
                );
                if (member != null) {
                    if (member.getIsLiveUser() == 1 || !isPromote(member)) {
                        continue;
                    }
                    final JdMatchLiveUser liveUser = new JdMatchLiveUser();
                    liveUser.setUserId(userId);
                    liveUser.setMatchId(matchLiveUser.getMatchId());
                    liveUser.setFormatId(matchLiveUser.getFormatArrangeId());
//                    2团队
                    liveUser.setType(1);
                    liveUser.setLiveRecordId(matchLiveUser.getRecordId());
                    final int flag = matchLiveUserMapper.insert(liveUser);
                    if (flag == 0) {
                        throw new SysRuntimeException("用户 ： " + member.getUserName() + ErrorCode.INSERT_ERROR.getMsg());
                    }
                }
            }
        } else {
            for (Integer groupId : matchLiveUser.getLiveUserList()) {
                final JdMatchLiveUser one = matchLiveUserMapper.selectOne(
                        new LambdaQueryWrapper<JdMatchLiveUser>()
                                .eq(JdMatchLiveUser::getFormatId, matchLiveUser.getFormatArrangeId())
                                .eq(JdMatchLiveUser::getGroupId, groupId)
                );
                if (one != null) {
                    continue;
                }
                if (groupId == 0) {
//                    白名单
                    final List<FormatLiveUser> whiteMemberList = formatLiveUserMapper.selectList(
                            new LambdaQueryWrapper<FormatLiveUser>()
                                    .eq(FormatLiveUser::getFormatId, matchLiveUser.getFormatArrangeId())
                                    .eq(FormatLiveUser::getGroupId, 0)
                    );
                    for (FormatLiveUser formatMember : whiteMemberList) {
                        JdMatchLiveUser liveUser = new JdMatchLiveUser();
                        liveUser.setUserId(formatMember.getUserId());
                        liveUser.setMatchId(matchLiveUser.getMatchId());
                        liveUser.setFormatId(matchLiveUser.getFormatArrangeId());
                        liveUser.setGroupId(0);
//                        2团队
                        liveUser.setType(2);
                        liveUser.setLiveRecordId(matchLiveUser.getRecordId());
                        final int flag = matchLiveUserMapper.insert(liveUser);
                        if (flag == 0) {
                            throw new SysRuntimeException("用户 ： " + formatMember.getUserName() + ErrorCode.INSERT_ERROR.getMsg());
                        }
                    }
                } else {
                    final List<JdMatchGroupUser> groupUsers = matchGroupUserMapper.selectList(
                            new LambdaQueryWrapper<JdMatchGroupUser>()
                                    .eq(JdMatchGroupUser::getGroupId, groupId)
                    );
                    for (JdMatchGroupUser groupUser : groupUsers) {
                        final FormatLiveUser member = formatLiveUserMapper.selectOne(
                                new LambdaQueryWrapper<FormatLiveUser>()
                                        .eq(FormatLiveUser::getFormatId, matchLiveUser.getFormatArrangeId())
                                        .eq(FormatLiveUser::getUserId, groupUser.getUserId())
                        );
                        if (member != null) {
                            if (member.getIsLiveUser() == 1 || !isPromote(member)) {
                                continue;
                            }
                            JdMatchLiveUser liveUser = new JdMatchLiveUser();
                            liveUser.setUserId(groupUser.getUserId());
                            liveUser.setMatchId(matchLiveUser.getMatchId());
                            liveUser.setFormatId(matchLiveUser.getFormatArrangeId());
                            liveUser.setGroupId(groupId);
//                             2团队
                            liveUser.setType(2);
                            liveUser.setLiveRecordId(matchLiveUser.getRecordId());
                            final int flag = matchLiveUserMapper.insert(liveUser);
                            if (flag == 0) {
                                throw new SysRuntimeException("用户 ： " + member.getUserName() + ErrorCode.INSERT_ERROR.getMsg());
                            }
                        }
                    }
                }
            }
        }
    }

    private boolean isPromote(FormatLiveUser member) {
        switch (member.getArrangeOrder()) {
            case 1:
//                初赛
                return true;
            case 2:
//                复赛
                FormatLiveUser first = formatLiveUserMapper.selectOne(
                        new LambdaQueryWrapper<FormatLiveUser>()
                                .eq(FormatLiveUser::getArrangeOrder, 1)
                                .eq(FormatLiveUser::getUserId, member.getUserId())
                                .eq(FormatLiveUser::getMatchId, member.getMatchId())
                );
                if (first == null) {
                    return false;
                }
                return first.getPromotionState() == 1;
            case 3:
//                决赛
                FormatLiveUser second = formatLiveUserMapper.selectOne(
                        new LambdaQueryWrapper<FormatLiveUser>()
                                .eq(FormatLiveUser::getArrangeOrder, 2)
                                .eq(FormatLiveUser::getUserId, member.getUserId())
                                .eq(FormatLiveUser::getMatchId, member.getMatchId())
                );
                if (second == null) {
//                    单程赛
                    return true;
                }
                return second.getPromotionState() == 1;
            default:
                return true;
        }
    }

    /**
     * 检测是否已经分配
     *
     * @param id              参赛员userId / 团队id
     * @param type            1个人2团队
     * @param formatArrangeId 赛程id
     */
    @Override
    public void isSetMatchLiveUser(Integer id, Integer type, Integer formatArrangeId) {
        JdMatchLiveUser liveUser;
        if (type == 1) {
            liveUser = matchLiveUserMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchLiveUser>()
                            .eq(JdMatchLiveUser::getFormatId, formatArrangeId)
                            .eq(JdMatchLiveUser::getUserId, id)
            );
        } else {
            final JdMatchGroupUser groupUser = matchGroupUserMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchGroupUser>()
                            .eq(JdMatchGroupUser::getGroupId, id)
                            .last(" limit 1")
            );
            liveUser = matchLiveUserMapper.selectOne(
                    new LambdaQueryWrapper<JdMatchLiveUser>()
                            .eq(JdMatchLiveUser::getFormatId, formatArrangeId)
                            .eq(JdMatchLiveUser::getUserId, groupUser.getUserId())
            );
        }
        if (liveUser != null) {
            throw new SysRuntimeException("该参赛员已分配");
        }
    }

    /**
     * 直播列表数量
     *
     * @param liveState 直播状态 -1全部 0未开始 1直播中 2直播结束
     * @param matchType 赛事分类
     * @param state     1关注2热门3最新
     * @param userId    当前登录用户
     * @param city      赛事城市
     * @param province  赛事省会
     * @return 总数
     */
    @Override
    public int liveListCount(Integer liveState, Integer matchType, Integer state, Integer userId, String city, String province) {
        return liveRecordMapperEx.liveListCount(liveState, matchType, state, userId, city, province);
    }

    /**
     * 直播列表
     *
     * @param liveState   直播状态 -1全部 0未开始 1直播中 2直播结束
     * @param matchType   赛事分类
     * @param convertPage 分页
     * @param state       1关注2热门3最新
     * @param userId      当前登录用户
     * @param city        赛事城市
     * @param province    赛事省会
     * @return LiveList
     */
    @Override
    public List<LiveList> liveList(int liveState, Integer matchType, String convertPage, Integer state, int userId, String city, String province) {
        return liveRecordMapperEx.liveList(liveState, matchType, convertPage, state, userId, city, province);
    }
}
